<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{MessageTemplateConfig, MessageRecord};
use app\service\MessageService;
use think\facade\{Db, Log};
use think\Request;

class MessageTemplateController extends BaseController
{
    /**
     * 获取消息模板列表
     */
    public function index(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 消息类型筛选
            if (isset($params['message_type'])) {
                $where[] = ['message_type', '=', $params['message_type']];
            }
            
            // 状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            $list = MessageTemplateConfig::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取消息模板列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 更新消息模板
     */
    public function update(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            $validate = validate('MessageTemplate');
            if (!$validate->check($params)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            
            $template = MessageTemplateConfig::where([
                'id' => $params['id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$template) {
                return json(['code' => 1, 'msg' => '模板不存在']);
            }
            
            $template->save([
                'template_id' => $params['template_id'],
                'status' => $params['status'],
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Log::error('更新消息模板失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 预览消息模板
     */
    public function preview(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $template = MessageTemplateConfig::where([
                'id' => $params['id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$template) {
                return json(['code' => 1, 'msg' => '模板不存在']);
            }
            
            // 获取模板变量示例值
            $variables = $this->getTemplateVariables($template->message_type);
            
            // 替换模板内容中的变量
            $content = $template->template_content;
            foreach ($variables as $key => $value) {
                $content = str_replace("{{$key}}", $value, $content);
            }
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => [
                'content' => $content,
                'variables' => $variables
            ]]);
        } catch (\Exception $e) {
            Log::error('预览消息模板失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取模板变量列表
     */
    public function variables(Request $request)
    {
        try {
            $message_type = $request->get('message_type');
            
            $variables = $this->getTemplateVariables($message_type);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $variables]);
        } catch (\Exception $e) {
            Log::error('获取模板变量列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 测试发送消息
     */
    public function test(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $template = MessageTemplateConfig::where([
                'id' => $params['id'],
                'merchant_id' => $merchant_id,
                'status' => 1
            ])->find();
            
            if (!$template) {
                return json(['code' => 1, 'msg' => '模板不存在或已禁用']);
            }
            
            $messageService = new MessageService();
            $result = $messageService->testSend($template, $params['test_user_id']);
            
            return json(['code' => 0, 'msg' => $result ? '发送成功' : '发送失败']);
        } catch (\Exception $e) {
            Log::error('测试发送消息失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取消息发送统计
     */
    public function statistics(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            $template_id = $request->get('template_id');
            
            $where = [['merchant_id', '=', $merchant_id]];
            if ($template_id) {
                $where[] = ['template_id', '=', $template_id];
            }
            
            $stats = [
                'total_sent' => MessageRecord::where($where)->count(), // 发送总数
                'success_count' => MessageRecord::where($where)->where('status', 1)->count(), // 成功数
                'fail_count' => MessageRecord::where($where)->where('status', 2)->count(), // 失败数
                'pending_count' => MessageRecord::where($where)->where('status', 0)->count() // 待发送数
            ];
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $stats]);
        } catch (\Exception $e) {
            Log::error('获取消息发送统计失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取消息发送记录
     */
    public function records(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 模板ID筛选
            if (!empty($params['template_id'])) {
                $where[] = ['template_id', '=', $params['template_id']];
            }
            
            // 发送状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            $list = MessageRecord::where($where)
                ->with(['user'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取消息发送记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取模板变量示例值
     */
    protected function getTemplateVariables($message_type)
    {
        // 根据消息类型返回对应的变量示例值
        $variables = [
            1 => [ // 公众号消息
                'first' => '您好,您的订单状态有更新',
                'keyword1' => '订单号:202401010001',
                'keyword2' => '订单状态:已发货',
                'keyword3' => '快递公司:顺丰快递',
                'keyword4' => '快递单号:SF1234567890',
                'remark' => '感谢您的使用'
            ],
            2 => [ // 小程序消息
                'thing1' => '订单状态更新通知',
                'character_string2' => '202401010001',
                'phrase3' => '已发货',
                'thing4' => '顺丰快递:SF1234567890',
                'time5' => date('Y-m-d H:i:s')
            ],
            3 => [ // 短信
                'order_no' => '202401010001',
                'status' => '已发货',
                'express' => '顺丰快递',
                'tracking_no' => 'SF1234567890'
            ]
        ];
        
        return $variables[$message_type] ?? [];
    }
} 